package com.project.controller;

import com.project.common.RedisCacheManager;
import com.project.common.ServerResponse;
import com.project.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class BaseController {
    @Autowired
    private RedisCacheManager redisCache;

    /**
     * 因为每次用户请求都会带着Token  在http中 获取用户的Token。 在根据Token获取 用户的Id 和 用户信息
     * 或者获取cookie里的信息.
     *
     * @return
     */
    protected User getCurrentUser() {
        //获取请求http的路径
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        User user = (User) request.getAttribute("userInfo_inter");
        if (user != null && user.getId() != null) {
            return user;
        }
        return null;
    }

    protected void delAllCookie(HttpServletRequest request, HttpServletResponse response) {
        //获取请求http的路径
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
//        User user = (User) request.getAttribute("userInfo_inter");
        request.setAttribute("userInfo_inter", null);
        Cookie[] cookies = request.getCookies();
        A:for (Cookie cookie : cookies) {
            switch (cookie.getName()) {
                case "userToken":
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break A;
                default:
                    break;
            }
        }
    }

}
